class Solution {  
public:  
    ListNode* removeElements(ListNode* head, int val) {  
        // 创建一个虚拟头节点  
        ListNode* dummy = new ListNode(0);  
        dummy->next = head;  
        ListNode* cur = dummy;  
  
        // 遍历链表，删除值为 val 的节点  
        while (cur->next != nullptr) {  
            if (cur->next->val == val) {  
                cur->next = cur->next->next;  
            } else {  
                cur = cur->next;  
            }  
        }  
  
        // 返回新的头节点  
        return dummy->next;  
    }  
};